﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Entities;

namespace StockFinder.ChartPatterns
{
    public class FlatBase
    {
        private const decimal MAX_DEPTH = 0.15M;
        private const int DAY_COUNT_THRESHOLD = 35;

        public bool DoesFit(Symbol symbol)
        {
            bool doesFit = false;

            decimal currentDayHigh = 0;
            decimal maximumHigh = 0;
            decimal maximumLow = 0;
            decimal depth = 0; //
            int dayCount = 0;

            //check we have (enough) prices
            if (symbol.Prices != null && symbol.Prices.Count > DAY_COUNT_THRESHOLD)
            {
                //setup new data
                currentDayHigh = symbol.Prices[0].High;
                maximumHigh = symbol.Prices[0].High;
                maximumLow = symbol.Prices[0].Low;

                //loop prices
                foreach (DailyPrice dailyPrice in symbol.Prices)
                {
                    //check not empty prices
                    if (dailyPrice.Close == 0)
                    {
                        break;
                    }

                    //new day
                    dayCount++;

                    //do we have a new peak?
                    if (dailyPrice.High > maximumHigh)
                    {
                        //yes
                        maximumHigh = dailyPrice.High;
                    }

                    //do we have a new low point?
                    if (dailyPrice.Low < maximumLow)
                    {
                        //yes
                        maximumLow = dailyPrice.Low;
                    }

                    //calculate depth
                    depth = (maximumHigh - maximumLow) / maximumHigh;

                    //have we breached depth threshold?
                    if (depth > MAX_DEPTH)
                    {
                        //yes
                        break;
                    }

                    //have we made it to 6 weeks of prices without breaching threshold
                    //and also not broken out of base i.e. current day is not highest price of base?
                    if (dayCount == DAY_COUNT_THRESHOLD &&
                        currentDayHigh < maximumHigh)
                    {
                        //yes so we might have possible flat base!
                        //set flag
                        doesFit = true;

                        break;
                    }
                }
            }

            return doesFit;
        }
    }
}
